package com.qianfeng.vhly.youshare.model;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.LinkedList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: vhly[FR]
 * Date: 15/2/7
 * Email: vhly@163.com
 */
public class Category {

    private String id;

    private String name;

    private String url;

    private List<Category> subCategories;

    public Category(){
        subCategories = new LinkedList<Category>();
    }

    public void parseJSON(JSONObject json){
        if (json != null) {
            try {
                id = json.getString("id");
                name = json.getString("name");
                url = json.getString("url");
                try {
                    // 获取子分类的内容，如果没有子分类了，将会出现一个异常，我们忽略即可。
                    JSONObject jsonObject = json.getJSONObject("cat_id");
                    // keys
                    JSONArray names = jsonObject.names();

                    if (names != null) {
                        int len = names.length();
                        for(int i = 0;i<len;i++){
                            String string = names.getString(i);

                            JSONObject object = jsonObject.getJSONObject(string);

                            Category category = new Category();

                            category.parseJSON(object);

                            subCategories.add(category);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public List<Category> getSubCategories() {
        return subCategories;
    }

    public String getUrl() {
        return url;
    }
}
